const fs = require('fs');

const glslfiles = getGlslFiles('.');

const { imports, shaderNames } = glslfiles.reduce((pv, v) =>
{
    const path = v;
    const name = v.replace('./', '').replace(/[\/\.-]/g, '_');

    pv.imports.push(`import ${name} from '${path}';`);
    pv.shaderNames.push(name);

    return pv;
}, { imports: [], shaderNames: [] });

const programs = [];
const shaderMap = shaderNames.reduce((pv, cv) =>
{
    pv[cv] = true;

    return pv;
}, {});
shaderNames.forEach((shaderName) =>
{
    const fs = shaderName.replace('vs', 'fs');
    if (shaderName !== fs && shaderMap[fs])
    {
        programs.push(`${shaderName}: { vertex: ${shaderName}, fragment: ${fs} }`);
    }
});

const indexStr = `/* eslint-disable camelcase */

${imports.join('\n')}

export const shaders = {
    ${shaderNames.join(',\n    ')}
};

export const programs = {
    ${programs.join(',\n    ')}
};

`;

fs.writeFileSync('index.ts', indexStr);

function getGlslFiles(currentPath, paths = [])
{
    if (currentPath.lastIndexOf('.glsl') === currentPath.length - '.glsl'.length)
    {
        paths.push(currentPath);

        return;
    }

    if (fs.statSync(currentPath).isDirectory())
    {
        const files = fs.readdirSync(currentPath);

        files.forEach((f) =>
        {
            getGlslFiles(`${currentPath}/${f}`, paths);
        });
    }

    return paths;
}

